# ===============================
# author: Paulo Trigo Silva (PTS)
# since: MAI.2010
# version: v02
# ===============================


#______________________________________________________________________________
# Baseado nos exemplos em:
# http://owlapi.sourceforge.net/documentation.html

#______________________________________________________________________________
# Python
import os

#______________________________________________________________________________
# Java
from org.semanticweb.owl.apibinding import OWLManager
from org.semanticweb.owl.util import SimpleURIMapper
from org.semanticweb.owl.io import RDFXMLOntologyFormat, OWLXMLOntologyFormat
from java.net import URI



#______________________________________________________________________________
class LeitorGravador:
   def __init__( self, strPhysicalURI, strOntologyURI="" ):
      # We first need to obtain a copy of an OWLOntologyManager, which, as the
      # name suggests, manages a set of ontologies.
      # An ontology is unique within an ontology manager.
      # To load multiple copies of an ontology, multiple managers would have to be used.
      self.manager = OWLManager.createOWLOntologyManager()
      # Por omissao a ontologyURI e o physicalURI sao iguais
      if strOntologyURI == "": strOntologyURI = strPhysicalURI
      self.associar( strPhysicalURI, strOntologyURI )


   def ler( self ):
      # We load an ontology; we use the physical URI (not the ontology URI)
      # (ask the manager to load the ontology)
      self.ontology = self.manager.loadOntologyFromPhysicalURI( self.physicalURI )


   def mostrarClasses( self ):
      # Print out all of the classes which are referenced in the ontology
      for c in self.ontology.getReferencedClasses(): print c


   def gravar( self, strToURI="", serializeFormat="RDF" ):
      return gravar( self.manager, self.ontology, strToURI, serializeFormat )


   def retirarDoGestor( self ):
      # Remove the ontology from the manager
      self.manager.removeOntology( self.ontology.getURI() )


   def obterOntologia( self ):
      return self.ontology


   #____________________________
   # Metodos Auxiliares (inicio)
   def associar( self, strPhysicalURI, strOntologyURI ):
      # All ontologies have a URI, which is used to identify the ontology.
      # Think of the ontology URI as the "name" of the ontology.
      # This URI frequently resembles a Web address (i.e. http://...),
      # but it is important to realise that the ontology URI might not necessarily be resolvable.
      # i.e., we may not get a document from the URI corresponding to the ontology URI, which represents the ontology.
      # In order to have a concrete representation of an ontology (e.g. an RDF/XML file),
      # we MAP the ontology URI to a PHYSICAL URI. We do this using a URIMapper.
      # We need to set up a mapping which points to a concrete file where the ontology will be stored.
      # (It's good practice to do this even if we don't intend to save the ontology).
      self.ontologyURI = URI.create( strOntologyURI )
      # Create a physical URI which can be resolved to point to where our ontology will be saved.
      self.physicalURI = URI.create( strPhysicalURI )
      # Set up a mapping, which maps the ontology URI to the physical URI
      self.mapper = SimpleURIMapper( self.ontologyURI, self.physicalURI )
      self.manager.addURIMapper( self.mapper )
   #_________________________
   # Metodos Auxiliares (fim)



#______________________________________________________________________________
# Funcoes Utilitarias
def gravar( manager, ontology, strToURI="", serializeFormat="RDF" ):
   """
   Dado um "manager" gravar uma "ontology" em "toURI" no formato "serializeFormat"
   "serializeFormat" pode ter valor "RDF" ou "OWL"
   """
   # Definir o formato (da estrutura XML) para seriar a ontoogia (OWL ou RDF)
   serializeXML = RDFXMLOntologyFormat()
   if serializeFormat == "OWL": serializeXML = OWLXMLOntologyFormat()
   # Now save a copy to another location in OWL/XML format
   # (i.e. disregard the format that the ontology was loaded in).
   if strToURI <> "":
      physicalURI = URI.create( strToURI  )
      manager.saveOntology( ontology, serializeXML, physicalURI )
   else:
      physicalURI = manager.getPhysicalURIForOntology( ontology )
      if not physicalURI:
         print "PTS ERRO"
         return
      manager.saveOntology( ontology, serializeXML )
   return physicalURI


def pathToStringURI( path, fileName ):
   # Atencao: a conversao de "path" em "URI" precisa de seguir as regras de formacao dos "URI"
   # - substituir \ por /
   path = path.replace( "\\", "/" )
   # - eliminar o indicador de "drive" (e.g., C:)
   path = path.split( ":" )[ 1 ]
   # - indicar que o "esquema" e' "file" e concatenar o nome do ficheiro a gerar
   stringURI = "file:" + path + "/" + fileName
   # - substituir todos os espaco em branco (dos "path" Windows) por "%20"
   stringURI = stringURI.replace( " ", "%20" )
   return stringURI



#______________________________________________________________________________
# Indicacao dos locais (URI) para leitura e gravacao da ontologia
# URI: para ler a ontologia
#fromURI = "http://www.co-ode.org/ontologies/pizza/2007/02/12/pizza.owl"
fromURI = pathToStringURI( os.getcwd(), "/solutions/z_myOnto.owl" )

# URI: para gravar a ontologia
toPath = currentDir = os.getcwd() # pasta corrente
toFileName = "/solutions/z_myOnto.owl"
toURI = pathToStringURI( toPath, toFileName )
#______________________________________________________________________________
if __name__ == "__main__":
   o = LeitorGravador( fromURI, "http://PIZZA" )
   o.ler()
   o.mostrarClasses()
   physicalURI = o.gravar( toURI, "OWL" )
   o.retirarDoGestor()
   print "-- /// --"
   print "fromURI = " + o.ontologyURI.toString()
   print "toURI   = " + physicalURI.toString()
   print "-- FIM --"


